<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px" class="main-search">
<!--      <el-form-item label="前" prop="startPrice">-->
<!--        <el-input-->
<!--          v-model="queryParams.startPrice"-->
<!--          placeholder="请输入前"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="后" prop="endPrice">-->
<!--        <el-input-->
<!--          v-model="queryParams.endPrice"-->
<!--          placeholder="请输入后"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="等级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择等级" clearable style="width: 160px">
          <el-option v-for="dict in dict.type.grade_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="业绩（万元）" align="center">
        <template slot-scope="scope">
          {{ scope.row.startPrice }}{{ scope.row.endPrice ? (' ~ ' + scope.row.endPrice) : '以上' }}
        </template>
      </el-table-column>
      <el-table-column label="等级" prop="grade" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.grade_type" :value="scope.row.grade"/>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="gradeName" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改佣金配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="业绩" prop="area">
          <el-col :span="10">
            <el-form-item prop="startPrice">
              <el-input v-model="form.startPrice" placeholder="请输入起始值(数字)"/>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2" style="text-align:center">-</el-col>
          <el-col :span="10">
            <el-form-item prop="endPrice">
              <el-input v-model="form.endPrice" placeholder="请输入结束值(数字)"/>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2" style="text-align:center">万元</el-col>
        </el-form-item>

        <el-col :span="22">
          <el-form-item label="等级" prop="grade">
            <el-select v-model="form.grade" placeholder="请选择星级">
              <el-option
                v-for="dict in dict.type.grade_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="22">
          <el-form-item label="名称" prop="gradeName">
            <el-input v-model="form.gradeName" placeholder="" maxlength="50"/>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {listYjStar, getYjStar, delYjStar, addYjStar, updateYjStar} from "@/api/customer/yjStar";

export default {
  name: "Config",
  dicts: ['total_customer_type', 'level_type', 'grade_type'],
  data() {
    const validateStart = (rule, value, callback) => {
      if (!!value) {
        // 1-1000的正则
        //const numReg = /^(?!00)(?:[0-9]{1,3}|1000)$/
        const numReg = /^[0-9]*$/
        if (!numReg.test(value)) {
          this.areaRules[0] = 1
          // 手动触发最外层form-item的正则验证
          this.areaBlur()
          return callback()
        }
        this.areaRules[0] = 0
        this.areaBlur()
        callback()
      } else {
        this.areaRules[0] = -1
        this.areaBlur()
        return callback()
      }
    }
    const validateEnd = (rule, value, callback) => {
      if (!!value) {
        // 1-1000的正则
        //const numReg = /^(?!00)(?:[0-9]{1,3}|1000)$/
        const numReg = /^[0-9]*$/
        if (!numReg.test(value)) {
          this.areaRules[1] = 1
          this.areaBlur()
          return callback()
        }
        this.areaRules[1] = 0
        this.areaBlur()
        callback()
      } else {
        this.areaRules[1] = 0
        this.areaBlur()
        return callback()
      }
    }
    // areaRules内值的含义：-1 提醒不能为空 0则表示正常 其他值为格式错误
    const validateArea = (rule, value, callback) => {
      if (this.areaRules.includes(-1)) {
        return callback(new Error('范围不能为空'))
      }
      if (this.areaRules[0] !== this.areaRules[1] || this.areaRules[0] === 1 || this.areaRules[1] === 1) {
        return callback(new Error('格式错误'))
      }
      if (this.form.endPrice) {
        if (Number(this.form.startPrice) > Number(this.form.endPrice)) {
          return callback(new Error('起始金额不能大于截止金额'))
        }
      }
      return callback()
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 佣金配置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startPrice: null,
        endPrice: null,
        grade: null,
        ratio: null,
        userType: null,
        status: null,
        createId: null
      },
      // 表单参数
      form: {},
      areaRules: [-1, 0],
      // 表单校验
      rules: {
        startPrice: [
          {
            required: true, message: "业绩开始金额不能为空", trigger: "blur",
            validator: validateStart
          }
        ],
        endPrice: [
          {
            required: true, message: "业绩结束金额不能为空", trigger: "blur",
            validator: validateEnd
          }
        ],
        grade: [
          {required: true, message: "星级不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 手动触发最外层form-item的正则验证
    areaBlur() {
      this.$refs['form'].validateField('area')
    },
    /** 查询佣金配置列表 */
    getList() {
      this.loading = true;
      listYjStar(this.queryParams).then(response => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        startPrice: null,
        endPrice: null,
        ratio: null,
        userType: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        createId: null,
        areaRules: [-1, -1],
        grade: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加业绩星级配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.areaRules = [0, 0];
      this.reset();
      const id = row.id || this.ids
      getYjStar(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改业绩星级配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateYjStar(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addYjStar(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return delYjStar(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>
